package com.youxue.listener;

import com.youxue.service.ClassService;
import com.youxue.service.CommentService;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 15c on 2018/2/13.
 * 课程总体评分监听
 */
public class ClassEvaluateGradeListener implements ServletContextListener {


    @Override
    public void contextInitialized(final ServletContextEvent sce) {
        final ClassService classService = (ClassService) WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(ClassService.class);
        final CommentService commentService = (CommentService) WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(CommentService.class);
        new Thread() {
            public void run() {
                while (true) {
                    try {
                        //查询具有评论的课程id（不重复）
                        List<Integer> classIdList = new ArrayList<Integer>();
                        classIdList = commentService.showAllComment();
                        //根据课程id计算课程评价总分
                        for (int i = 0; i < classIdList.size(); i++) {
                            //计算得分
                            double resultScore = 0;
                            resultScore = commentService.sumAClassTotalScore(classIdList.get(i)) / commentService.showAClassAllCommentCount(classIdList.get(i));

                            int result = classService.reviseAClassScore(classIdList.get(i), resultScore);
                        }
                        //休眠12小时（一天统计两次）
                        Thread.sleep(12 * 60 * 60 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
